package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by karkarrotxu on 2016/3/3.
 */
public final class ApiChatUtil {
    private static Logger logger = LoggerFactory.getLogger(ApiChatUtil.class);

    private ApiChatUtil() {
    }

    public static final String CHAT_CREATE = Configuration.getString("chat.create.url");
    public static final String CHAT_UPDATE = Configuration.getString("chat.update.url");
    public static final String CHAT_DELETE = Configuration.getString("chat.del.url");
    public static final String CHAT_OPEN = Configuration.getString("chat.open.url");
    public static final long SYSTEM_UID = -1527;
    public static final String SECRET_KEY = Configuration.getString("chat.secret.key");
    public static final String LIVECHAT_SECRET_KEY = Configuration.getString("livechat.secret.key");
    public static final int AGENT_TYPE_PGC = 2;
    public static final int LIVECHAT_AGENTTYPE = Configuration.getInt("livechat.agenttype", 171);
    public static final String CHAT_SYS_SEND = Configuration.getString("chat.sys.send.url");
    public static final String CHAT_SYS_PACKAGE_HISTORY = Configuration.getString("chat.sys.package.history.url");
    public static final String CHAT_SYS_HINT_MSG = Configuration.getString("chat.sys.hint.msg");
    public static final String DEFAULT_ICON = "http://pic5.qiyipic.com/image/20131024/v_100585163_m_601_m1.jpg";

    public static long createChat(long uid, long qipuId, String chatRoomName, long startTime, long endTime, int checkType) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", AGENT_TYPE_PGC + "");
        map.put("name", chatRoomName);
        map.put("creater", uid + "");
        map.put("qipuid", qipuId + "");
        map.put("start_time", startTime + "");
        map.put("end_time", endTime + "");
        map.put("check_type", checkType + "");
        map.put("sign", sign(map, SECRET_KEY));

        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_CREATE, null, map);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            logger.info("[ApiChatUtil][createChat][success]{}", JSON.toJSONString(map));
            return result.getJSONObject("data").getLongValue("room_id");
        }
        logger.info("[ApiChatUtil][createChat][fail]{}", JSON.toJSONString(map));
        return -1;
    }

    public static long deleteChat(long chatroomId) {
        return deleteChat(chatroomId, SYSTEM_UID);
    }

    public static long deleteChat(long chatroomId, long uid) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", AGENT_TYPE_PGC + "");
        map.put("room_id", chatroomId + "");
        map.put("uid", uid + "");
        map.put("type", "3");
        map.put("sign", sign(map, SECRET_KEY));
        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_DELETE, null, map);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            logger.info("[ApiChatUtil][deleteChat][success]{}", JSON.toJSONString(map));
            return 0;
        }
        logger.info("[ApiChatUtil][deleteChat][fail]{}", JSON.toJSONString(map));
        return -1;
    }

    public static long updateChat(long uid, String chatRoomId, long startTime, long endTime, int checkType) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", AGENT_TYPE_PGC + "");
        map.put("creater", uid + "");
        map.put("room_id", chatRoomId);
        map.put("start_time", startTime + "");
        map.put("end_time", endTime + "");
        map.put("check_type", checkType + "");
        map.put("sign", sign(map, SECRET_KEY));

        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_UPDATE, null, map);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            logger.info("[ApiChatUtil][updateChat][success]{}", JSON.toJSONString(map));
            return 0;
        }
        logger.info("[ApiChatUtil][updateChat][fail]{}", JSON.toJSONString(map));
        return -1;
    }

    public static int openChat(long chatRoomId, long uid) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", AGENT_TYPE_PGC + "");
        map.put("room_id", chatRoomId + "");
        map.put("uid", uid + "");
        map.put("sign", sign(map, SECRET_KEY));

        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_OPEN, null, map);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            logger.info("[ApiChatUtil][openChat][success]{}", JSON.toJSONString(map));
            return 0;
        }
        logger.info("[ApiChatUtil][openChat][fail]{}", JSON.toJSONString(map));
        return -1;
    }

    public static String sign(Map<String, String> params, String secretKey) {
        SortedMap<String, String> sortedParams = new TreeMap<String, String>(params);
        sortedParams.remove("sign");
        StringBuilder sb = new StringBuilder();
        for (String key : sortedParams.keySet()) {
            String val = sortedParams.get(key);
            sb.append(key).append("=").append(StringUtils.defaultIfEmpty(val, "")).append("|");
        }
        return DigestUtils.md5Hex(sb.append(secretKey).toString());
    }

    public static long doSysNoticeStart(long chatRoomId, long qipuId, String icon) {
        JSONObject msgObj = new JSONObject();
        msgObj.put("qd", qipuId);
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", LIVECHAT_AGENTTYPE + "");
        map.put("msg_type", "8");
        map.put("room_id", chatRoomId + "");
        map.put("content", CHAT_SYS_HINT_MSG);
        map.put("icon", icon);
        map.put("nickname", "epg");
        map.put("msg_ext", msgObj.toJSONString());
        map.put("media_type", "1");
        map.put("sign", sign(map, LIVECHAT_SECRET_KEY));
        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_SYS_SEND, null, map);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            logger.info("[ApiChatUtil][doSysNoticeStart][success]{}", JSON.toJSONString(map));
            return 0;
        }
        logger.info("[ApiChatUtil][doSysNoticeStart][fail]{}", JSON.toJSONString(map));
        return -1;
    }

    /**
     * 打包聊天室消息作为弹幕
     * @param chatRoomId
     * @param liveId
     * @param tvId
     * @param startTime
     * @param endTime
     * @return
     */
    public static int packageHistoryMessage(long programId, long chatRoomId, long liveId, long tvId, long channelId, long startTime,long endTime) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("agenttype", LIVECHAT_AGENTTYPE + "");
        map.put("room_id", chatRoomId + "");
        map.put("live_id", liveId + "");
        map.put("tv_id", tvId + "");
        map.put("channel_id", channelId + "");
        map.put("type", "1");
        map.put("start_time", startTime + "");
        map.put("end_time", endTime + "");
        map.put("sign", sign(map, LIVECHAT_SECRET_KEY));
        JSONObject result = ApiHttpRequestUtil.doPost(CHAT_SYS_PACKAGE_HISTORY, null, map);
        try {
            if (null != result) {
                if (Constants.CODE_SUC.equals(result.getString("code"))) {

                    logger.info("[ApiChatUtil][packageHistoryMessage][success]{}", JSON.toJSONString(map) + "|" + result.toJSONString());
                    WriteSystemLogUtil.getInstance().writeProgramLog(programId, Constants.LogType.CHAT_PACKAGE_HISTORY.getIndex(), "[ApiChatUtil][packageHistoryMessage][success]| "+ JSON.toJSONString(map) + "| " + result.toJSONString());
                    return 0;
                } else {
                    logger.info("[ApiChatUtil][packageHistoryMessage][fail]{}", JSON.toJSONString(map) + "|" + result.toJSONString());
                    WriteSystemLogUtil.getInstance().writeProgramLog(programId, Constants.LogType.CHAT_PACKAGE_HISTORY.getIndex(), "[ApiChatUtil][packageHistoryMessage][fail]| "+ JSON.toJSONString(map) + "| " + result.toJSONString());
                    return -1;
                }
            } else {
                logger.info("[ApiChatUtil][packageHistoryMessage][fail]{}", JSON.toJSONString(map) + "| result == null");
                WriteSystemLogUtil.getInstance().writeProgramLog(programId, Constants.LogType.CHAT_PACKAGE_HISTORY.getIndex(), "[ApiChatUtil][packageHistoryMessage][fail]"+ JSON.toJSONString(map) + "| result == null,maybe network error ?");
                return -1;
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("[ApiChatUtil][packageHistoryMessage][Exception]{}", JSON.toJSONString(map) + "|" + e);
            WriteSystemLogUtil.getInstance().writeProgramLog(programId, Constants.LogType.CHAT_PACKAGE_HISTORY.getIndex(), "[ApiChatUtil][packageHistoryMessage][Exception]| " + JSON.toJSONString(map) + "|" + e);
            return -1;
        }
    }



}
